<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单号" prop="orderNo">
        <el-input
          v-model="queryParams.orderNo"
          placeholder="请输入订单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="orderStatus">
        <el-select v-model="queryParams.orderStatus" placeholder="请选择订单状态" clearable>
          <el-option
            v-for="dict in dict.type.ec_order_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="支付" prop="paymentStatus">
        <el-select v-model="queryParams.paymentStatus" placeholder="请选择支付状态" clearable>
          <el-option
            v-for="dict in dict.type.ec_pay_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="收货人" prop="receiverName">
        <el-input
          v-model="queryParams.receiverName"
          placeholder="请输入收货人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="电话" prop="receiverPhone">
        <el-input
          v-model="queryParams.receiverPhone"
          placeholder="请输入电话"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户" prop="userId">
        <id-selector
          v-model="queryParams.userId"
          placeholder="请选择用户"
          dialog-title="选择用户"
          :api-function="listUser"
          :get-api-function="getUser"
          id-field="userId"
          name-field="userName"
          id-label="用户ID"
          name-label="用户名"
          search-label="用户名"
          search-placeholder="请输入用户名"
          :extra-columns="[{prop: 'nickName', label: '昵称'}, {prop: 'phonenumber', label: '手机号'}]"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['fun:order:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderList">
      <el-table-column label="发货" align="center" width="180">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="success"
            plain
            icon="el-icon-truck"
            @click="handleShipment(scope.row)"
            title="商品发货"
          >商品发货</el-button>
        </template>
      </el-table-column>
      <el-table-column label="关联商品" align="center" width="130">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            plain
            icon="el-icon-goods"
            @click="handleOrderItems(scope.row)"
            title="查看订单商品"
          >关联商品</el-button>
        </template>
      </el-table-column>
      <el-table-column label="订单号" align="center" prop="orderNo" />
      <el-table-column label="创建组织" align="center" width="120">
        <template slot-scope="scope">
          <span>{{ getDeptName(scope.row.orgId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户" align="center" prop="userId" width="120">
        <template slot-scope="scope">
          <span>{{ getUserName(scope.row.userId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" align="center" prop="orderStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.ec_order_status" :value="scope.row.orderStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="支付方式" align="center" prop="paymentType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.ec_pay_type" :value="scope.row.paymentType"/>
        </template>
      </el-table-column>
      <el-table-column label="支付状态" align="center" prop="paymentStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.ec_pay_status" :value="scope.row.paymentStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="配送方式" align="center" prop="deliveryType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.ec_delivery_type" :value="scope.row.deliveryType"/>
        </template>
      </el-table-column>
      <el-table-column label="订单总金额" align="center" prop="totalAmount" />
      <el-table-column label="实付金额" align="center" prop="paymentAmount" />
      <el-table-column label="运费" align="center" prop="freightAmount" />
      <el-table-column label="优惠金额" align="center" prop="discountAmount" />
      <el-table-column label="收货人姓名" align="center" prop="receiverName" />
      <el-table-column label="收货人电话" align="center" prop="receiverPhone" />
      <el-table-column label="收货省份" align="center" prop="receiverProvince" />
      <el-table-column label="收货城市" align="center" prop="receiverCity" />
      <el-table-column label="收货区县" align="center" prop="receiverDistrict" />
      <el-table-column label="收货详细地址" align="center" prop="receiverAddress" />
      <el-table-column label="订单备注" align="center" prop="orderNote" />
      <el-table-column label="确认收货状态" align="center" prop="confirmStatus" />
      <el-table-column label="删除状态" align="center" prop="deleteStatus" />
      <el-table-column label="支付时间" align="center" prop="paymentTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.paymentTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="发货时间" align="center" prop="deliveryTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.deliveryTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="收货时间" align="center" prop="receiveTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.receiveTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="评价时间" align="center" prop="commentTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.commentTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>

    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改订单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="订单号" prop="orderNo">
          <el-input v-model="form.orderNo" placeholder="请输入订单号" />
        </el-form-item>
        <el-form-item label="用户" prop="userId">
          <IdSelector v-model="form.userId" :listApi="listUser" :getApi="getUser" placeholder="请选择用户" />
        </el-form-item>
        <el-form-item label="订单状态" prop="orderStatus">
          <el-select v-model="form.orderStatus" placeholder="请选择订单状态">
            <el-option
              v-for="dict in dict.type.ec_order_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="支付方式" prop="paymentType">
          <el-select v-model="form.paymentType" placeholder="请选择支付方式">
            <el-option
              v-for="dict in dict.type.ec_pay_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="确认收货时间" prop="receiveTime">
          <el-date-picker clearable
            v-model="form.receiveTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择确认收货时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="评价时间" prop="commentTime">
          <el-date-picker clearable
            v-model="form.commentTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择评价时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 发货信息对话框 -->
    <el-dialog :title="shipmentTitle" :visible.sync="shipmentOpen" width="600px" append-to-body>
      <el-form ref="shipmentForm" :model="shipmentForm" :rules="shipmentRules" label-width="80px">
        <el-form-item label="订单号" prop="orderNo">
          <el-input v-model="shipmentForm.orderNo" placeholder="订单号" disabled />
        </el-form-item>
        <el-form-item label="物流类型" prop="logisticsType">
          <el-radio-group v-model="shipmentForm.logisticsType">
            <el-radio :label="1">快递配送</el-radio>
            <el-radio :label="2">同城配送</el-radio>
            <el-radio :label="3">虚拟商品</el-radio>
            <el-radio :label="4">用户自提</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="物流单号" prop="logisticsNo" v-if="shipmentForm.logisticsType === 1">
          <el-input v-model="shipmentForm.logisticsNo" placeholder="请输入物流单号" />
        </el-form-item>
        <el-form-item label="物流公司" prop="logisticsCompany" v-if="shipmentForm.logisticsType === 1">
          <id-selector
            v-model="shipmentForm.logisticsCompany"
            placeholder="请选择物流公司"
            dialog-title="选择物流公司"
            :api-function="listLogisticsCompany"
            :get-api-function="getLogisticsCompany"
            id-field="id"
            name-field="expName"
            id-label="物流公司ID"
            name-label="物流公司名称"
            search-label="物流公司名称"
            search-placeholder="请输入物流公司名称"
            :extra-columns="[{prop: 'com', label: '物流公司代码'}, {prop: 'phone', label: '联系电话'}, {prop: 'url', label: '官网地址'}]"
            @change="handleLogisticsCompanyChange"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitShipmentForm">确 定</el-button>
        <el-button @click="shipmentCancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listOrder, getOrder, delOrder, addOrder, updateOrder, listUser, getUser } from "@/api/fun/order"
import { addLogistics, wechatShipping } from "@/api/fun/logistics"
import { listLogisticsCompany, getLogisticsCompany } from "@/api/fun/logisticsCompany"
import { getDept } from "@/api/system/dept"
import CacheManager from '@/utils/cacheManager'
import IdSelector from "@/components/IdSelector"

export default {
  name: "Order",
  dicts: ['ec_order_status', 'ec_pay_type', 'ec_pay_status', 'ec_delivery_type'],
  components: {
    IdSelector
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单表格数据
      orderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderNo: null,
        userId: null,
        orderStatus: null,
        paymentType: null,
        paymentStatus: null,
        deliveryType: null,
        totalAmount: null,
        paymentAmount: null,
        freightAmount: null,
        discountAmount: null,
        couponAmount: null,
        receiverName: null,
        receiverPhone: null,
        receiverProvince: null,
        receiverCity: null,
        receiverDistrict: null,
        receiverAddress: null,
        receiverZip: null,
        orderNote: null,
        confirmStatus: null,
        deleteStatus: null,
        paymentTime: null,
        deliveryTime: null,
        receiveTime: null,
        commentTime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        orderNo: [
          { required: true, message: "订单号不能为空", trigger: "blur" }
        ],
        userId: [
          { required: true, message: "用户ID不能为空", trigger: "blur" }
        ],
        orderStatus: [
          { required: true, message: "订单状态不能为空", trigger: "change" }
        ],
        totalAmount: [
          { required: true, message: "订单总金额不能为空", trigger: "blur" }
        ],
        paymentAmount: [
          { required: true, message: "实付金额不能为空", trigger: "blur" }
        ],
        receiverName: [
          { required: true, message: "收货人姓名不能为空", trigger: "blur" }
        ],
        receiverPhone: [
          { required: true, message: "收货人电话不能为空", trigger: "blur" }
        ],
        receiverProvince: [
          { required: true, message: "收货省份不能为空", trigger: "blur" }
        ],
        receiverCity: [
          { required: true, message: "收货城市不能为空", trigger: "blur" }
        ],
        receiverDistrict: [
          { required: true, message: "收货区县不能为空", trigger: "blur" }
        ],
        receiverAddress: [
          { required: true, message: "收货详细地址不能为空", trigger: "blur" }
        ]
      },
      // 发货对话框相关数据
      shipmentOpen: false,
      shipmentTitle: "",
      shipmentForm: {},
      shipmentRules: {
        // 订单号在发货表单中通常是预填的，保持必填
        orderNo: [
          { required: true, message: "订单号不能为空", trigger: "blur" }
        ],
        // 物流类型必填
        logisticsType: [
          { required: true, message: "请选择物流类型", trigger: "change" }
        ],
        // 物流单号：快递配送时必填
        logisticsNo: [
          {
            validator: (rule, value, callback) => {
              if (this.shipmentForm.logisticsType === 1) {
                // 快递配送时必填
                if (!value) {
                  callback(new Error('快递配送时，物流单号不能为空'));
                } else {
                  callback();
                }
              } else {
                // 其他类型时不验证
                callback();
              }
            },
            trigger: ['blur', 'change']
          }
        ],
        // 物流公司：快递配送时必填
        logisticsCompany: [
          {
            validator: (rule, value, callback) => {
              if (this.shipmentForm.logisticsType === 1) {
                // 快递配送时必填
                if (!value) {
                  callback(new Error('快递配送时，物流公司不能为空'));
                } else {
                  callback();
                }
              } else {
                // 其他类型时不验证
                callback();
              }
            },
            trigger: ['blur', 'change']
          }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {    /** 根据部门ID获取部门名称 */
    getDeptName(deptId) {
      return CacheManager.getDeptName(deptId, getDept)
    },
    /** 查询订单列表 */
    getList() {
      this.loading = true;
      listOrder(this.queryParams).then(response => {
        this.orderList = response.rows;
      this.total = response.total;
      this.loading = false;
    });
    },
    /** 获取用户名 */
    getUserName(userId) {
      return CacheManager.getUserName(userId, getUser)
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        orderId: null,
        orderNo: null,
        userId: null,
        orderStatus: null,
        paymentType: null,
        paymentStatus: null,
        deliveryType: null,
        totalAmount: null,
        paymentAmount: null,
        freightAmount: null,
        discountAmount: null,
        couponAmount: null,
        receiverName: null,
        receiverPhone: null,
        receiverProvince: null,
        receiverCity: null,
        receiverDistrict: null,
        receiverAddress: null,
        receiverZip: null,
        orderNote: null,
        confirmStatus: null,
        deleteStatus: null,
        paymentTime: null,
        deliveryTime: null,
        receiveTime: null,
        commentTime: null,
        createTime: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.orderId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加订单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const orderId = row.orderId || this.ids
      getOrder(orderId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改订单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.orderId != null) {
            updateOrder(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addOrder(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const orderIds = row.orderId || this.ids;
      this.$modal.confirm('是否确认删除订单编号为"' + orderIds + '"的数据项？').then(function() {
        return delOrder(orderIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 关联商品按钮操作 */
    handleOrderItems(row) {
      this.$router.push({
        path: '/order/item',
        query: {
          orderNo: row.orderNo
        }
      })
    },
    /** 商品发货按钮操作 */
    handleShipment(row) {
      this.shipmentOpen = true;
      this.shipmentTitle = "新增发货";
      this.shipmentForm = {
        orderId: row.orderId, // 添加订单ID
        orderNo: row.orderNo,
        logisticsType: 1, // 默认选择快递配送
        logisticsNo: null,
        logisticsCompany: null,
        logisticsStatus: '1' // 默认状态为待发货
      };
    },
    /** 发货对话框取消按钮 */
    shipmentCancel() {
      this.shipmentOpen = false;
      this.resetShipmentForm();
    },
    /** 发货表单重置 */
    resetShipmentForm() {
      this.shipmentForm = {
        orderId: null, // 添加订单ID
        orderNo: null,
        logisticsType: 1, // 默认选择快递配送
        logisticsNo: null,
        logisticsCompany: null,
        logisticsStatus: '1'
      };
      this.$refs["shipmentForm"] && this.$refs["shipmentForm"].resetFields();
    },
    /** 发货表单提交 */
    submitShipmentForm() {
      this.$refs["shipmentForm"].validate(valid => {
        if (valid) {
          // 先查询订单详情获取收货地址手机号
          getOrder(this.shipmentForm.orderId).then(orderResponse => {
            const orderData = orderResponse.data;
            const receiverPhone = orderData.receiverPhone; // 收货地址手机号
            
            // 先添加物流信息
            addLogistics(this.shipmentForm).then(response => {
              this.$modal.msgSuccess("发货信息添加成功");
              
              // 调用微信发货接口
              const wechatData = {
                orderId: this.shipmentForm.orderId,
                logistics_type: this.shipmentForm.logisticsType
              };
              
              // 如果是快递配送，添加快递信息
              if (this.shipmentForm.logisticsType === 1) {
                wechatData.shipping_list = [{
                  tracking_no: this.shipmentForm.logisticsNo
                }];
                wechatData.contact = {
                  receiver_contact: receiverPhone
                };
              }
              
              wechatShipping(wechatData).then(wechatResponse => {
                this.$modal.msgSuccess("微信发货通知发送成功");
              }).catch(error => {
                console.error("微信发货通知发送失败:", error);
                this.$modal.msgWarning("物流信息已保存，但微信发货通知发送失败");
              });
              
              this.shipmentOpen = false;
              this.resetShipmentForm();
              this.getList(); // 刷新列表
            }).catch(error => {
              console.error("发货信息添加失败:", error);
            });
          }).catch(error => {
            console.error("查询订单详情失败:", error);
            this.$modal.msgError("查询订单详情失败，无法获取收货地址信息");
          });
        }
      });
    },
    /** 物流公司选择变化处理 */
    handleLogisticsCompanyChange(value) {
      // 可以在这里处理物流公司变化的逻辑
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('fun/order/export', {
        ...this.queryParams
      }, `order_${new Date().getTime()}.xlsx`)
    },
    /** 用户列表API */
    listUser(params) {
      return listUser(params)
    },
    /** 获取用户详情API */
    getUser(id) {
      return getUser(id)
    },
    /** 物流公司列表API */
    listLogisticsCompany(params) {
      return listLogisticsCompany(params)
    },
    /** 获取物流公司详情API */
    getLogisticsCompany(id) {
      return getLogisticsCompany(id)
    }
  }
};
</script>
